﻿using BLL;
using System;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using Thksoft.Module.DataDetail.Master;
using Utility.Helper;

namespace Thksoft.Module.DataDetail
{
    public partial class YearCapital : BaseUI.BasePage
    {
        private Sys_CompanyBLL companyBLL = new Sys_CompanyBLL();
        private QX_PLANYEARAPPLYBLL planYearApplayBLL = new QX_PLANYEARAPPLYBLL();

        public Capital master
        {
            get
            {
                return (Capital)base.Master;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //master.FORM_QUERY.Click += btnSelect_Click;
            if (!IsPostBack)
            {
                txtDate.Value = DateTime.Now.Year.ToString();
                //master.CTitle = "年资金明细";
            }
        }

        #region 代码块

        protected void BindData(bool iffirst)
        {
            decimal comid = lognUser.USER_COMPANY;
            if (ddlCom.Value != -1)
            {
                comid = ddlCom.Value;
            }
            var comidStr = companyBLL.GetCompanyFatherAndChildByID(comid);
            var sql = @"SELECT T1.N_YEARAPP_ID,
       T1.N_YEAR,
       T1.N_BUSINESS_ID,
       T1.C_YEARAPP_NAME,
       T1.N_COMPANY_ID,
       T5.CMY_NAME,
       T1.N_USER_ID,
       to_char(T1.D_OPERATOR_TIME, 'yyyy-mm-dd HH24:MI:SS') D_OPERATOR_TIME,
       T1.C_REAMRK,
       DECODE(T1.N_BUSINESS_STATE,0,'注销',1,'启用',2,'归档','其它') AS N_BUSINESS_STATE,
       T2.USER_NAME AS C_USER_NAME,
       SUM(decode(T4.N_TYPE2, 1, T3.N_AMOUNT, 0)) INTO_SUM,
       SUM(decode(T4.N_TYPE2, 2, T3.N_AMOUNT, 0)) OUT_SUM
  FROM QX_PLANYEARAPPLY T1
 INNER JOIN SYS_USER T2
    ON T1.N_USER_ID = T2.USER_ID
 INNER JOIN QX_PLANYEAR_DETAIL T3
    ON T1.N_YEARAPP_ID = T3.N_YEARAPP_ID
 INNER JOIN QS_PROJECT T4
    ON T3.N_PROID = T4.N_PROID
 INNER JOIN SYS_COMPANY T5
    ON T1.N_COMPANY_ID = T5.CMY_ID
  WHERE T1.N_YEARAPP_ID = T3.N_YEARAPP_ID
AND T1.N_COMPANY_ID IN ({0}) AND T4.N_TYPE=2 {1}
 GROUP BY T1.N_YEARAPP_ID,
          T1.N_YEAR,
          T1.N_BUSINESS_ID,
          T1.C_YEARAPP_NAME,
          T1.N_COMPANY_ID,
          T5.CMY_NAME,
          T1.N_USER_ID,
          T1.D_OPERATOR_TIME,
          T1.C_REAMRK,
          T1.N_BUSINESS_STATE,
          T2.USER_NAME";
            if (txtDate.Value != "-1" && txtDate.Value != "" && comidStr != null)
            {
                int year = int.Parse(txtDate.Value.Substring(0, 4));
                sql = string.Format(sql, comidStr, "AND T1.N_YEAR = " + year);
            }
            else if (comidStr != null)
            {
                sql = string.Format(sql, comidStr, null);
            }
            else if (txtDate.Value != "-1" && txtDate.Value != "")
            {
                int year = int.Parse(txtDate.Value.Substring(0, 4));
                sql = string.Format(sql, -1, "AND T1.N_YEAR = " + year);
            }
            else
            {
                sql = string.Format(sql, -1, null);
            }
            var orderbyStr = (string)ViewState["ORDER"];
            if (!string.IsNullOrEmpty(orderbyStr))
            {
                sql += " ORDER BY " + orderbyStr + " " + (string)ViewState["ORDER_TYPE"];
            }

            DataTable dt = planYearApplayBLL.Query(sql);
            var row = dt.NewRow();
            row["C_USER_NAME"] = "合计";
            row["N_YEARAPP_ID"] = DBNull.Value;
            row["N_BUSINESS_ID"] = 0;
            row["C_YEARAPP_NAME"] = DBNull.Value;
            row["INTO_SUM"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["INTO_SUM"]));
            row["OUT_SUM"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["OUT_SUM"]));
            dt.Rows.Add(row);
            grvShow.DataSource = dt;
            grvShow.DataBind();
        }

        //分页
        protected void PageIng_DataBinding(object sender, EventArgs e)
        {
            BindData(false);
        }

        //设置奇偶行颜色
        protected void grvShow_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string buid = ((Label)e.Row.FindControl("lblBuid")).Text;
                if (buid == "0")
                {
                    ((Panel)e.Row.FindControl("Panel2")).Visible = false;
                }
            }
        }

        /// <summary>
        /// GridView标题排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvShow_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            string SortOrder, OrderDire;
            SortOrder = ViewState["ORDER"] == null ? null : (string)ViewState["ORDER"];
            OrderDire = ViewState["ORDER_TYPE"] == null ? null : (string)ViewState["ORDER_TYPE"];
            if (SortOrder == sPage)
            {
                if (OrderDire == "Desc")
                    OrderDire = "ASC";
                else
                    OrderDire = "Desc";
            }
            else
            {
                SortOrder = e.SortExpression;
                OrderDire = "ASC";
            }
            ViewState["ORDER"] = SortOrder;
            ViewState["ORDER_TYPE"] = OrderDire;
            BindData(true);
            //分页绑定数据
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            //var where = "";

            ////公司
            //if (ddlCom.Value != -1)
            //{
            //    where += "T1.N_COMPANY_ID = " + ddlCom.Value;
            //}
            //else
            //{
            //    if (lognUser.USER_LOGINNAME == "SUPER")
            //    {
            //        where = "1=1";
            //    }
            //    else
            //    {
            //        where += "T1.N_COMPANY_ID IN(" + companyBLL.GetCompanyFatherAndChildByID(CurrentUserCompanyID) + ")";
            //    }
            //}
            //ViewState["WHERE"] = where;
            BindData(true);
        }

        #endregion 代码块

        #region 代码块

        protected void DetailClick(object sender, EventArgs e)
        {
            var key = txtDate.Value;
            if (string.IsNullOrEmpty(key))
            {
                MessageBox.Show(this, "没有获取到年申请Key");
                return;
            }
            //FORM_DETAL_PAGE.BindData(Convert.ToDecimal(key));
            master.Check = false;
        }

        #endregion 代码块

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPrint_Click1(object sender, EventArgs e)
        {
            if (grvShow == null || grvShow.Rows.Count == 0)
            {
                MessageBox.Show(Page, "【系统提示】未能查询出数据，暂时不能导出，请先查询数据。");
                return;
            }

            decimal comid = lognUser.USER_COMPANY;
            if (ddlCom.Value != -1)
            {
                comid = ddlCom.Value;
            }
            var comidStr = companyBLL.GetCompanyFatherAndChildByID(comid);
            var sql = @"SELECT T1.N_YEARAPP_ID,
       T1.N_YEAR,
       T1.N_BUSINESS_ID,
       T1.C_YEARAPP_NAME,
       T1.N_COMPANY_ID,
       T5.CMY_NAME,
       T1.N_USER_ID,
       to_char(T1.D_OPERATOR_TIME, 'yyyy-mm-dd HH24:MI:SS') D_OPERATOR_TIME,
       T1.C_REAMRK,
       DECODE(T1.N_BUSINESS_STATE,0,'注销',1,'启用',2,'归档','其它') AS N_BUSINESS_STATE,
       T2.USER_NAME AS C_USER_NAME,
       SUM(decode(T4.N_TYPE2, 1, T3.N_AMOUNT, 0)) INTO_SUM,
       SUM(decode(T4.N_TYPE2, 2, T3.N_AMOUNT, 0)) OUT_SUM
  FROM QX_PLANYEARAPPLY T1
 INNER JOIN SYS_USER T2
    ON T1.N_USER_ID = T2.USER_ID
 INNER JOIN QX_PLANYEAR_DETAIL T3
    ON T1.N_YEARAPP_ID = T3.N_YEARAPP_ID
 INNER JOIN QS_PROJECT T4
    ON T3.N_PROID = T4.N_PROID
 INNER JOIN SYS_COMPANY T5
    ON T1.N_COMPANY_ID = T5.CMY_ID
  WHERE T1.N_YEARAPP_ID = T3.N_YEARAPP_ID
AND T1.N_COMPANY_ID IN ({0}) AND T4.N_TYPE=2 {1}
 GROUP BY T1.N_YEARAPP_ID,
          T1.N_YEAR,
          T1.N_BUSINESS_ID,
          T1.C_YEARAPP_NAME,
          T1.N_COMPANY_ID,
          T5.CMY_NAME,
          T1.N_USER_ID,
          T1.D_OPERATOR_TIME,
          T1.C_REAMRK,
          T1.N_BUSINESS_STATE,
          T2.USER_NAME";
            if (txtDate.Value != "-1" && txtDate.Value != "" && comidStr != null)
            {
                int year = int.Parse(txtDate.Value.Substring(0, 4));
                sql = string.Format(sql, comidStr, "AND T1.N_YEAR = " + year);
            }
            else if (comidStr != null)
            {
                sql = string.Format(sql, comidStr, null);
            }
            else if (txtDate.Value != "-1" && txtDate.Value != "")
            {
                int year = int.Parse(txtDate.Value.Substring(0, 4));
                sql = string.Format(sql, -1, "AND T1.N_YEAR = " + year);
            }
            else
            {
                sql = string.Format(sql, -1, null);
            }
            var orderbyStr = (string)ViewState["ORDER"];
            if (!string.IsNullOrEmpty(orderbyStr))
            {
                sql += " ORDER BY " + orderbyStr + " " + (string)ViewState["ORDER_TYPE"];
            }

            DataTable dt = planYearApplayBLL.Query(sql);

            var html = "<table border='1'>";
            html += "<tr>";
            html += "<th>年</th>";
            html += "<th>名称</th>";
            html += "<th>申请人</th>";
            html += "<th>申请时间</th>";
            html += "<th>状态</th>";
            html += "<th>合计（流入）</th>";
            html += "<th>合计（流出）</th>";
            html += "<th>备注</th>";
            html += "</tr>";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                html += "<tr>";

                if (i % 2 == 0)
                {
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["N_YEAR"].ToString() + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["C_YEARAPP_NAME"].ToString() + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["C_USER_NAME"].ToString() + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + (dt.Rows[i]["D_OPERATOR_TIME"] == DBNull.Value ? "" : dt.Rows[i]["D_OPERATOR_TIME"].DateFormat("yyyy-MM-dd HH:mm:ss")) + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["N_BUSINESS_STATE"].ToString() + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["INTO_SUM"].ToString() + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["OUT_SUM"].ToString() + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + (dt.Rows[i]["C_REAMRK"] == DBNull.Value ? "" : dt.Rows[i]["C_REAMRK"].ToString()) + "</td>";
                }
                else
                {
                    html += "<td>" + dt.Rows[i]["N_YEAR"].ToString() + "</td>";
                    html += "<td>" + dt.Rows[i]["C_YEARAPP_NAME"].ToString() + "</td>";
                    html += "<td>" + dt.Rows[i]["C_USER_NAME"].ToString() + "</td>";
                    html += "<td>" + (dt.Rows[i]["D_OPERATOR_TIME"] == DBNull.Value ? "" : dt.Rows[i]["D_OPERATOR_TIME"].DateFormat("yyyy-MM-dd HH:mm:ss")) + "</td>";
                    html += "<td>" + dt.Rows[i]["N_BUSINESS_STATE"].ToString() + "</td>";
                    html += "<td>" + dt.Rows[i]["INTO_SUM"].ToString() + "</td>";
                    html += "<td>" + dt.Rows[i]["OUT_SUM"].ToString() + "</td>";
                    html += "<td>" + (dt.Rows[i]["C_REAMRK"] == DBNull.Value ? "" : dt.Rows[i]["C_REAMRK"].ToString()) + "</td>";
                }

                html += "</tr>";
            }

            html += "<tr>";
            html += "<td colspan=\"5\" align=\"center\">合计</td>";
            html += "<td>" + dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["INTO_SUM"])) + "</td>";
            html += "<td>" + dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["OUT_SUM"])) + "</td>";
            html += "<td></td>";
            html += "</tr>";
            html += "</table>";
            toExecl1(html, (txtDate.Value == "" ? "" : txtDate.Value + "年") + "资金明细");
        }
    }
}